<?php

declare(strict_types=1);

namespace app\model\esxsys;

use app\eslib\EsUtils;
use app\model\GoodsModel;
use think\facade\Db;
use think\Model;

/**
 * 查询关键词 模型类
 */
class SearchesModel extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'esxsys_searches';

    // 自动时间戳
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    public static function addSearch($word, $type = '', $userId = 0)
    {
        self::addSearchLog($userId, $word, $type);
        $table = (new static())->table;
        $id = Db::table($table)->where('keyword', $word)->where('type', $type)->value('id');
        if ($id) {
            Db::table($table)->where('id')->inc('stat_search_quantity')->update(['updated_at' => time()]);
            return $id;
        }
        $id = Db::table($table)->insertGetId([
            'keyword' => $word,
            'item_type' => $type,
            'created_at' => time(),
        ]);
        return $id;
    }

    public static function addSearchLog($userId, $word, $type = '')
    {
        $table = 'esxsys_search_log';
        Db::table($table)->insert([
            'keyword' => $word, 'item_type' => $type, 'user_id' => $userId,
            'date_ymd' => date('Y-m-d'), 'created_at' => time()
        ]);
    }

    public static function addSearchItem($userId, $word, $type = '')
    {
        $table = 'esxsys_search_item';
        Db::table($table)->insert([
            'keyword' => $word, 'item_type' => $type, 'user_id' => $userId,
            'date_ymd' => date('Y-m-d'), 'created_at' => time()
        ]);
    }

    public static function getWordsList($count)
    {
        return self::order('stat_search_quantity', 'desc')->limit($count)->column('keyword');
    }

    public static function getGoodsList($pageSize = 10)
    {
        $goodsIds = Db::table('esxsys_search_item')->order('stat_search_quantity desc')->limit($pageSize)->column('item_id');
        if (!$goodsIds) {
            $goodsIds = GoodsModel::order('id desc')->limit($pageSize)->column('id');
        }
        $list = GoodsModel::where('id', 'in', $goodsIds)->field('id, goods_name, price, icon, expire_date')->select();
        return $list;
    }
}
